package com.hsck.order.kds.base.isnoam.view

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager

class SpacesItemDecoration(
    private val space: Int,
    private val header: Boolean = false,
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State,
    ) {
        val position = parent.getChildAdapterPosition(view)
        if (header) {
            outRect.top = space
            outRect.bottom = space
            outRect.left = space
            outRect.right = space
        } else {
            // 普通项处理
            val layoutManager = parent.layoutManager as StaggeredGridLayoutManager
            val spanCount = layoutManager.spanCount

            // 计算列索引
            val column = position % spanCount

            // 左右间距处理：确保左右两侧与屏幕对齐，同时列间距均匀
            val totalSpace = space * (spanCount - 0) // 总的间距（不包括屏幕边缘）
            val itemWidthSpace = totalSpace / spanCount // 每个Item分配的平均间距

            outRect.left = column * itemWidthSpace / spanCount  // 左边距
            outRect.right = itemWidthSpace - outRect.left // 右边距

            // 上下间距
            if (position >= spanCount) {
                outRect.top = space // 非第一行顶部添加间距
            }
            outRect.bottom = space / 2 // 所有项底部添加间距
        }
    }
}

